//
//  AppDelegate.m
//  GoBigMarket
//
//  Created by legend on 16/8/3.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "AppDelegate.h"
#import "AddressViewController.h"
#import "WelcomViewController.h"
#import "HomeViewController.h"
#import "NewFeatureViewController.h"
#import "MyProductsTool.h"
#import <AlipaySDK/AlipaySDK.h>
#import "ShopingCartViewController.h"
#import "WXApi.h"
#import "WXApiManager.h"
#import "RootViewController.h"
#import "BeeCloud.h"
@interface AppDelegate ()<WXApiDelegate, BeeCloudDelegate>

@end

@implementation AppDelegate{
    float _lng;
    float _lat;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    
    return  [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    if (![BeeCloud handleOpenUrl:url]) {
        
        //handle其他类型的url
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    self.window.rootViewController = [[UIViewController alloc]init];
    //向微信注册wxd930ea5d5a258f4f
    [BeeCloud initWithAppID:@"f6afa03b-055e-4749-acfa-122bf8d0b841" andAppSecret:@"108ce905-e395-446a-8df6-1e02f993a84d"];
    DLog(@"UUID___ %@ TOKEN___ %@ PHONE___ %@", GETUUID, GETTOKEN, GETPHONE);
    [BeeCloud initWeChatPay:@"wxdeaf20c134765733"];
    // 要使用百度地图，请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定 generalDelegate参数
    // 在此处输入您的授权Key
    // 原始dwjmVauF5TWPYFfFnoZjOmof
    // 临瑞科技测试: eAdKQqt9eUTgKBq8KGyBGhfswGfGmt8K
    BOOL ret = [_mapManager start:@"eAdKQqt9eUTgKBq8KGyBGhfswGfGmt8K" generalDelegate:nil];
    if (!ret) {
        DLog(@"manager start failed!");
    }else {
        DLog(@"manager start success!");
    }
    
    //    获取当前程序的info.plist中的Bundle version版本号，和沙盒中的版本号比较。
    //    info.plist中版本号的键值
    NSString *key = (__bridge NSString *)kCFBundleVersionKey;
    //    当前软件版本号
    NSString *newEditionNum = [NSBundle mainBundle].infoDictionary[key];
    //    沙盒中的版本号
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *sandBoxEditionNum = [defaults stringForKey:key];
    //    比较两者的大小(或者判断[newEditionNum isEqualToString:sandBoxEditionNum])
    if ([newEditionNum compare:sandBoxEditionNum] == NSOrderedDescending) {
        //        当前版本号存储到沙盒
        [defaults setObject:newEditionNum forKey:key];
        //        同步写入
        [defaults synchronize];
        //根控制器为新特性控制器
//        self.window.rootViewController = [[NewFeatureViewController alloc]init];
         [UIApplication sharedApplication].keyWindow.rootViewController = [[NewFeatureViewController alloc]init];
    }else{

        if (GETTOKEN && GETUUID && GETPHONE) {
            [CQNetWorkTools
             POSTWithURL:PostLingLogin par:@{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN} success:^(id responseObject) {
                 if ([[responseObject valueForKey:@"Err"] integerValue]!=0) {
                     [self logIn];
                     NSUserDefaults *account = [NSUserDefaults standardUserDefaults];
                     [account setObject:@"未登录" forKey:LOGIN_STATUS];
                     [account synchronize];
                     
                 }else{
                     //更新token
                     [[NSUserDefaults standardUserDefaults]setObject:[responseObject valueForKey:@"Token"] forKey: @"Token"];
                     //获取Main.storyboard中的首页
                     UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                     UITabBarController *tabBar = [mainStory instantiateViewControllerWithIdentifier:@"tabBarId"];
                     self.window.rootViewController = tabBar;
                     NSUserDefaults *account = [NSUserDefaults standardUserDefaults];
                     [account setObject:@"已登录" forKey:LOGIN_STATUS];
                     [account synchronize];
                 }
             } filed:^(NSError *error) {
                 DLog(@"token ERROR %@",error);
             }];
        }else{
            [self logIn];
            NSUserDefaults *account = [NSUserDefaults standardUserDefaults];
            [account setObject:@"未登录" forKey:LOGIN_STATUS];
            [account synchronize];
        }
}
    return YES;
}

//token登录失败和未登录时要跳页面
- (void)logIn{
//    WelcomViewController *welcomeVC = [[WelcomViewController alloc]init];
//    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:welcomeVC];
//      [UIApplication sharedApplication].keyWindow.rootViewController = nav;
    
    //获取Main.storyboard中的首页
    UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UITabBarController *tabBar = [mainStory instantiateViewControllerWithIdentifier:@"tabBarId"];
    self.window.rootViewController = tabBar;

}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    //中断响应
    
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"XuanZeAddress"];
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    
    if (![BeeCloud handleOpenUrl:url]) {
        UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        RootViewController *rootVC = [story instantiateViewControllerWithIdentifier:@"tabBarId"];
        self.window.rootViewController = rootVC;
        rootVC.selectedIndex = 0;
        //handle其他类型的url
    }
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            DLog(@"result = %@",resultDic);
            if ( [[resultDic objectForKey:@"resultStatus"] intValue]== 9000)
            {
                
                UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
                RootViewController *rootVC = [story instantiateViewControllerWithIdentifier:@"tabBarId"];
                self.window.rootViewController = rootVC;
                rootVC.selectedIndex = 0;
            }
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            DLog(@"result = %@",resultDic);
            // 解析 auth code
            if ( [[resultDic objectForKey:@"resultStatus"] intValue]== 9000)
            {
                UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
                RootViewController *rootVC = [story instantiateViewControllerWithIdentifier:@"tabBarId"];
                self.window.rootViewController = rootVC;
                rootVC.selectedIndex = 0;
            }
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            DLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return YES;
}

//#pragma mark - 小红点
//- (void)CartRedPoint {
//    if (GETShopId) {
//    [CQNetWorkTools POSTWithURL:ShopCartGetProducts par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN, @"Duuid":GETUUID,@"ShopId":GETShopId} success:^(id responseObject) {
//        UIStoryboard *story= [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//        HomeViewController *home = story.instantiateInitialViewController;
//        home.navigationController.tabBarController.viewControllers[2].tabBarItem.badgeValue = [NSString stringWithFormat:@"%@", [responseObject objectForKey:@"TotalCount"]];
//        if ([[NSString stringWithFormat:@"%@", [responseObject objectForKey:@"TotalCount"]] isEqualToString:@"0"]) {
//            home.navigationController.tabBarController.viewControllers[2].tabBarItem.badgeValue = nil;
//        }
//    } filed:^(NSError *error) {
//        NSLog(@"%@", error);
//    }];
//    }
//}

@end
